package com.sn.author.utils;

import com.sn.author.common.context.SessionHelper;
import com.sn.author.common.exception.BadRequestException;
import com.sn.author.domain.entity.ImportAccount;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author xiaom
 * @Date 2020/9/21 10:31
 * @Version 1.0.0
 * @Description <>
 **/
public class Export {

    private List<String> rowTitles = new ArrayList<>();

    public XSSFWorkbook wb;

    private String fileName;

    public Export(List<String> titles,String fileName) {
        this.rowTitles = titles;
        this.fileName = fileName;
    }

    /**
     * 生成一个WorkBook表格
     */
    public Export generateWorkBookTitle() {
        if(this.rowTitles.isEmpty()){
            throw new BadRequestException("生成WorkBook文件失败,因为传递的标题参数为空");
        }
        XSSFWorkbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("sheet1");
        Row titleRow = sheet.createRow(0);

        for (int i = 0; i < this.rowTitles.size(); i++) {
            titleRow.createCell(i).setCellValue(this.rowTitles.get(i));
        }
        this.wb = wb;
        return this;
    }

    public Export writeData(List list){
        return this;
    }

    public void download() {
        OutputStream outputStream;
        HttpServletResponse response = SessionHelper.getContextResponse();
        try {
            //设置ContentType请求信息格式
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
